package com.qf.shop.sms.listener;

import com.qf.shop.common.constants.RabbitMQCons;
import com.qf.shop.common.pool.ShopExcutors;
import com.qf.shop.common.vo.Email;
import com.qf.shop.common.vo.SmsVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.util.List;

@Component
@Slf4j
public class SendEmail {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String fromUser;

    @RabbitListener(queues = RabbitMQCons.EMAIL_QUEUE)
    public void send(Email email, Channel channel, Message message) {
        ShopExcutors.getExecutor().submit(() -> {
            log.debug("Email:{}", email);
            try {
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                helper.setSubject(email.getTitle());
                helper.setText(email.getContent(), true);
                String[] strArray = {""};
                helper.setTo(email.getToUserList().toArray(strArray)); // 收件人
                helper.setFrom(fromUser); // 发件人
//            javaMailSender.send(mimeMessage);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (Exception e) {
                log.error("发送邮件失败", e);
            }
        });


    }
}
